package com.songVersion.services.impl;

import java.util.List;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.songVersion.services.CountingManager;
import com.songVersion.utils.PMF;

public abstract class CountingManagerImpl<T> extends ManagerImpl<T> implements
		CountingManager<T>
{
	protected boolean isFiltered;
	protected String filter;
	protected String declaredParameters;
	protected Map parameters;
	
	@SuppressWarnings("unchecked")
	public List<T> getMaxSearched(int maxItems)
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(t.getClass());
		query.setOrdering("hits desc");
		query.setRange(0, maxItems);
		setParams();
		if (isFiltered)
		{
			query.setFilter(filter);
			query.declareParameters(declaredParameters);
		}
		List<T> l = null;
		
		try
		{
			if (isFiltered) l = (List<T>) query.executeWithMap(parameters);
			else l = (List<T>) query.execute();

			initResultList(l);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		pm.close();
		return l;
	}
	
	/*
	 * if you need to filter the query, please, specify filtes here.
	 * 
	 */
	protected void setParams()
	{
		
	}
	
	/*
	 * For composite objects, you need to loop on the result list and to ensure all entities are loaded. 
	 * This is a bug of the ORM system. 
	 */
	protected void initResultList(List<T> l)
	{
		l.size();//avoid lazy loading!
	}
	public T save()
	{
		T t = loadBean();
		
		if (t == null)
		{
			System.out.println("newwwww");
			t = newBean();
		}
		
		addHit(t);
		
		return super.save(t);
	}
	
	protected T loadBean()
	{
		System.out.println("loadBean!");
		PersistenceManager pm = PMF.get().getPersistenceManager();
		T t = doLoadBean(pm);
		
		if (t == null)
			t = newBean();
		pm.close();
		return t;
	}
	protected abstract T doLoadBean(PersistenceManager pm);
	protected abstract T newBean();
	protected abstract void addHit(T t);
}
